﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using itau.im.entidade;
using EnterpriseLibraryWrapper;
using System.Data;
using System.Xml;

namespace itau.im.dado
{
    public class CalendarioMock : ICalendarioDAO
    {
        #region Métodos

        public IList<PracaCalendario> ObterPracasCalendario()
        {
            List<PracaCalendario> listaRetorno = new List<PracaCalendario>();
            IDataAccessWrapper data = null;
            DataSet dsRetorno = new DataSet();

            try
            {
                data = EnterpriseLibraryFactory.GetDataAccess();

                dsRetorno = ObterPracasCalendarioDoXML();

                if (dsRetorno.Tables.Count > 0 && dsRetorno.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow linha in dsRetorno.Tables[0].Rows)
                    {
                        listaRetorno.Add(EntidadeFactory.getPracaCalendario(linha));
                    }
                }

                return listaRetorno;
            }
            catch (DadosException ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            catch (Exception ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            finally
            {
                listaRetorno = null;
                data.Dispose();
                data = null;
                dsRetorno = null;
            }

            return new List<PracaCalendario>();
        }

        private DataSet ObterPracasCalendarioDoXML()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(System.Threading.Thread.GetDomain().BaseDirectory + System.Configuration.ConfigurationSettings.AppSettings["DB2_MOCK_FOLDER"] + "\\DadosPracaCalendario.xml");

            DataSet ds = new DataSet();

            if (xml != null)
            {
                ds.Tables.Add(new DataTable("Pracas"));

                XmlNodeList cabecalho = xml.SelectNodes("Resultado/Colunas/Coluna");

                foreach (XmlNode node in cabecalho)
                {
                    ds.Tables[0].Columns.Add(node.Attributes["nome"].Value, Type.GetType(node.Attributes["tipo"].Value));
                }

                XmlNodeList dados = xml.SelectNodes("Resultado/Dados/Linhas/Linha");

                foreach (XmlNode node in dados)
                {
                    XmlNodeList celulas = node.SelectNodes("Celulas/Celula");

                    DataRow dr = ds.Tables[0].NewRow();

                    foreach (XmlNode celula in celulas)
                    {
                        dr[celula.Attributes["nome"].Value] = celula.InnerText;
                    }

                    ds.Tables[0].Rows.Add(dr);
                }
            }

            return ds;
        }

        public int CalcularDiasCorridosEntre(DateTime data1, DateTime data2)
        {
            int diascorridosentre;

            try
            {
                diascorridosentre = Convert.ToInt32(data2.ToOADate() - data1.ToOADate());
                return diascorridosentre;
            }
            catch (DadosException ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            catch (Exception ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            finally
            {
            }

            return diascorridosentre = 0;
        }

        public int CalcularDiasUteisEntre(DateTime data1, DateTime data2)
        {
            int intDiasUteisEntre = 0;

            try
            {

                CalendarioBS.DatasServiceSoapClient cal = new CalendarioBS.DatasServiceSoapClient();

                CalendarioBS.DiasUteisResponse iintDiasUteisEntre = cal.ObtemQuantidadeDiasUteis(data1.Day.ToString(),
                                                                 data1.Month.ToString(),
                                                                 data1.Year.ToString(),
                                                                 data2.Day.ToString(),
                                                                 data2.Month.ToString(),
                                                                 data2.Year.ToString(), "", "", "");

                if (iintDiasUteisEntre.CodigoRetorno == 0)
                {
                    intDiasUteisEntre = Math.Abs(iintDiasUteisEntre.DiasUteis);
                }
                else
                {
                    throw new Exception("Serviço de Calendário retornou codigo de erro: " + iintDiasUteisEntre.CodigoRetorno + " Mensagem: " + iintDiasUteisEntre.ReasonCode);
                }

                return intDiasUteisEntre;
            }
            catch (DadosException ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            catch (Exception ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            finally
            {
                intDiasUteisEntre = 0;
            }

            return intDiasUteisEntre = 0;
        }

        public void ConfigurarCalendarioGerador(int diasExtensaoCurva)
        {
            CalendarioSingleton.Configurar(diasExtensaoCurva);
        }

        public IList<String> ObtemFeriadosNacionaisIntervalo(DateTime data1, DateTime data2)
        {
            List<String> lista = new List<string>();
            CalendarioBS.DatasServiceSoapClient cal = new CalendarioBS.DatasServiceSoapClient();

            try
            {
                if (CalendarioSingleton.HouveConsulta())
                {
                    lista = CalendarioSingleton.ObtemFeriadosNacionaisIntervalo(data1, data2);
                }
                else
                {
                    string DiaDataInicial = data1.Day.ToString();
                    string MesDataInicial = data1.Month.ToString();
                    string AnoDataInicial = data1.Year.ToString();

                    string DiaDataFinal = data2.Day.ToString();
                    string MesDataFinal = data2.Month.ToString();
                    string AnoDataFinal = data2.Year.ToString();

                    CalendarioBS.InfoFeriadosResponse feriadosResponse = cal.ObtemFeriadosNacionaisIntervalo(DiaDataInicial,
                                                                                                             MesDataInicial,
                                                                                                             AnoDataInicial,
                                                                                                             DiaDataFinal,
                                                                                                             MesDataFinal,
                                                                                                             AnoDataFinal);

                    foreach (Object item in feriadosResponse.EstadosInfo)
                    {
                        string strDate = ((CalendarioBS.FeriadoInfoClass)item).Data_Feriado;
                        System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();
                        dtfi.ShortDatePattern = "dd/MM/yyyy";
                        dtfi.DateSeparator = "/";
                        DateTime objDate = Convert.ToDateTime(strDate, dtfi);
                        lista.Add(objDate.ToString("yyyyMMdd"));
                    }
                }
            }
            catch (DadosException ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            catch (Exception ex)
            {
                EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
            }
            finally
            {
                cal.Abort();
                cal.Close();
            }

            return lista;
        }

        public bool EhFeriadoNacional(DateTime data)
        {
            {
                CalendarioBS.DatasServiceSoapClient cal = new CalendarioBS.DatasServiceSoapClient();

                try
                {
                    string DiaData = data.Day.ToString();
                    string MesData = data.Month.ToString();
                    string AnoData = data.Year.ToString();

                    CalendarioBS.InfoUmFeriadoResponse umFeriadoResponse = cal.ObtemIsFeriadoNacional(DiaData,
                                                                                                        MesData,
                                                                                                        AnoData);
                    return umFeriadoResponse.EstadoInfo.IsFeriado.Equals("S");
                }
                catch (DadosException ex)
                {
                    EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
                }
                catch (Exception ex)
                {
                    EnterpriseLibraryFactory.GetExceptionHandler().HandleException(ex, "ErrosDados");
                }
                finally
                {
                    cal.Abort();
                    cal.Close();
                }

                return false;
            }
        }

        #endregion
    }
}
